package com.swxc.smartorder.network

import android.content.Context
import android.support.v4.app.FragmentManager
import android.widget.Toast

import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.HttpParams
import com.lzy.okgo.model.Response
import com.lzy.okgo.request.base.Request
import com.swxc.smartorder.app.Config
import com.swxc.smartorder.app.ConfigSPS
import com.swxc.smartorder.app.GlobalAPI
import com.swxc.smartorder.ui.dialog.LoadingDialog
import com.swxc.smartorder.utils.AppSharePreferenceMgr
import com.swxc.smartorder.utils.MD5Util

import java.io.File

/**
 * Author   Administrator
 * Date     2018/3/30
 * Desc     eg
 *
 * @author Administrator
 */
class NetworkHelper(private val mContext: Context?, private val mFragmentManager: FragmentManager) {
    private var strToken: String? = null


    /**
     * get请求
     *
     * @param requestUrl
     * @param params
     * @param listener
     */
    fun getRequest(requestUrl: String, params: HttpParams, listener: NetWorkHelperBack?) {
        strToken = AppSharePreferenceMgr.get(mContext, ConfigSPS.TOKEN, "") as String
        val loadingDialog = LoadingDialog()
        val signString = sign(params)
        if (!signString?.isBlank()!!) {
            params.put("sign", signString)
        }
        OkGo.get<String>(requestUrl)
                .params("access_token", strToken)
                .params(params)
                .execute(object : StringCallback() {
                    override fun onStart(request: Request<String, out Request<*, *>>?) {
                        super.onStart(request)
                        loadingDialog.show(mFragmentManager, "loadDialog")
                    }

                    override fun onFinish() {
                        super.onFinish()
                        loadingDialog.dismissAllowingStateLoss()
                    }

                    override fun onSuccess(response: Response<String>) {
                        listener?.requestSuccess(response.body())

                    }

                    override fun onError(response: Response<String>) {
                        super.onError(response)
                        Toast.makeText(mContext, "服务器异常", Toast.LENGTH_SHORT).show()
                        listener?.requestFail()
                    }
                })
    }

    /**
     * post请求  带token
     *
     * @param requestUrl
     * @param params
     * @param listener
     */
    fun postRequest(requestUrl: String, params: HttpParams, listener: NetWorkHelperBack?) {
        strToken = AppSharePreferenceMgr.get(mContext, ConfigSPS.TOKEN, "") as String
        val loadingDialog = LoadingDialog()
        val signString = sign(params)
        if (!signString?.isBlank()!!) {
            params.put("sign", signString)
        }
        OkGo.post<String>(requestUrl)
                .params("access_token", strToken)
                .params(params)
                .execute(object : StringCallback() {
                    override fun onStart(request: Request<String, out Request<*, *>>?) {
                        super.onStart(request)
                        loadingDialog.show(mFragmentManager, "loadDialog")
                    }

                    override fun onFinish() {
                        super.onFinish()
                        loadingDialog.dismissAllowingStateLoss()
                    }

                    override fun onSuccess(response: Response<String>) {
                        listener?.requestSuccess(response.body())

                    }

                    override fun onError(response: Response<String>) {
                        super.onError(response)
                        Toast.makeText(mContext, "服务器异常", Toast.LENGTH_SHORT).show()
                        listener?.requestFail()
                    }
                })
    }

    /**
     * get请求
     *
     * @param requestUrl
     * @param params
     * @param listener
     */
    fun getRequestWithoutToken(requestUrl: String, params: HttpParams, listener: NetWorkHelperBack?) {
        val loadingDialog = LoadingDialog()
        val signString = sign(params)
        if (!signString?.isBlank()!!) {
            params.put("sign", signString)
        }
        OkGo.get<String>(requestUrl)
                .params(params)
                .execute(object : StringCallback() {
                    override fun onStart(request: Request<String, out Request<*, *>>?) {
                        super.onStart(request)
                        loadingDialog.show(mFragmentManager, "loadDialog")
                    }

                    override fun onFinish() {
                        super.onFinish()
                        loadingDialog.dismissAllowingStateLoss()
                    }

                    override fun onSuccess(response: Response<String>) {
                        listener?.requestSuccess(response.body())

                    }

                    override fun onError(response: Response<String>) {
                        super.onError(response)
                        Toast.makeText(mContext, "服务器异常", Toast.LENGTH_SHORT).show()
                        listener?.requestFail()
                    }
                })
    }

    /**
     * get请求
     *
     * @param requestUrl
     * @param params
     * @param listener
     */
    fun putRequestWithoutToken(requestUrl: String, params: HttpParams, listener: NetWorkHelperBack?) {
        val loadingDialog = LoadingDialog()
        val signString = sign(params)
        if (!signString?.isBlank()!!) {
            params.put("sign", signString)
        }
        OkGo.put<String>(requestUrl)
                .params(params)
                .execute(object : StringCallback() {
                    override fun onStart(request: Request<String, out Request<*, *>>?) {
                        super.onStart(request)
                        loadingDialog.show(mFragmentManager, "loadDialog")
                    }

                    override fun onFinish() {
                        super.onFinish()
                        loadingDialog.dismissAllowingStateLoss()
                    }

                    override fun onSuccess(response: Response<String>) {
                        listener?.requestSuccess(response.body())

                    }

                    override fun onError(response: Response<String>) {
                        super.onError(response)
                        Toast.makeText(mContext, "服务器异常", Toast.LENGTH_SHORT).show()
                        listener?.requestFail()
                    }
                })
    }

    /**
     * get请求
     *
     * @param requestUrl
     * @param params
     * @param listener
     */
    fun putRequest(requestUrl: String, params: HttpParams, listener: NetWorkHelperBack?) {

        strToken = AppSharePreferenceMgr.get(mContext, ConfigSPS.TOKEN, "") as String
        val signString = sign(params)
        if (!signString?.isBlank()!!) {
            params.put("sign", signString)
        }
        OkGo.put<String>(requestUrl)
                .params("access_token", strToken)
                .params(params)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>) {
                        listener?.requestSuccess(response.body())

                    }

                    override fun onError(response: Response<String>) {
                        super.onError(response)
                        Toast.makeText(mContext, "服务器异常", Toast.LENGTH_SHORT).show()
                    }
                })
    }


    /**
     * 登录页面
     *
     * @param loginUrl
     * @param params
     * @param listener
     */
    fun login(loginUrl: String, params: HttpParams, listener: NetWorkHelperBack?) {
        val loadingDialog = LoadingDialog()
        params.put("client_secret", "2692e5ef9dc34482b5993a311f086090")
        params.put("grant_type", "password")
        params.put("scope", "servicecenter")
        params.put("client_id", "824bce609110472a9dcf837ada0053e1")
        val signString = sign(params)
        if (!signString?.isBlank()!!) {
            params.put("sign", signString)
        }
        OkGo.post<String>(loginUrl)
                .params(params)

                .execute(object : StringCallback() {
                    override fun onStart(request: Request<String, out Request<*, *>>?) {
                        super.onStart(request)
                        loadingDialog.show(mFragmentManager, "loadDialog")
                    }

                    override fun onSuccess(response: Response<String>) {
                        listener?.requestSuccess(response.body())

                    }

                    override fun onError(response: Response<String>) {
                        super.onError(response)
                        Toast.makeText(mContext, "服务器异常", Toast.LENGTH_SHORT).show()
                    }

                    override fun onFinish() {
                        super.onFinish()
                        loadingDialog.dismiss()
                    }
                })
    }


    fun refreshToken(loginUrl: String, listener: NetWorkHelperBack?) {
        val loadingDialog = LoadingDialog()
        val refreshToken = AppSharePreferenceMgr.get(mContext, ConfigSPS.REFRESH_TOKEN, "") as String

        val params = HttpParams()

        params.put("client_secret", "2692e5ef9dc34482b5993a311f086090")
        params.put("grant_type", "refresh_token")
        params.put("refresh_token", refreshToken)
        params.put("client_id", "824bce609110472a9dcf837ada0053e1")
        val signString = sign(params)
        if (!signString?.isBlank()!!) {
            params.put("sign", signString)
        }
        OkGo.post<String>(loginUrl)
                .params(params)


                .execute(object : StringCallback() {
                    override fun onStart(request: Request<String, out Request<*, *>>?) {
                        super.onStart(request)
                        loadingDialog.show(mFragmentManager, "loadDialog")
                    }

                    override fun onSuccess(response: Response<String>) {
                        listener?.requestSuccess(response.body())

                    }

                    override fun onError(response: Response<String>) {
                        super.onError(response)
                        Toast.makeText(mContext, "服务器异常", Toast.LENGTH_SHORT).show()
                    }

                    override fun onFinish() {
                        super.onFinish()
                        loadingDialog.dismiss()
                    }
                })
    }

    /**
     * 处理工单
     *
     * @param content
     * @param mOrderId
     * @param mStaffId
     * @param type
     * @param listener
     */
    fun handOrder(content: String, imageId: String, mOrderId: Long?, mStaffId: Long?, type: String, listener: NetWorkHelperBack?) {
        val loadingDialog = LoadingDialog()

        strToken = AppSharePreferenceMgr.get(mContext, ConfigSPS.TOKEN, "") as String
        val httpParams = HttpParams()
        httpParams.put("content", content)
        httpParams.put("imageIds", imageId)
        httpParams.put("id", mOrderId!!)
        httpParams.put("staffId", mStaffId!!)
        httpParams.put("serviceType", type)
        httpParams.put("access_token", strToken)
        val signString = sign(httpParams)
        if (!signString?.isBlank()!!) {
            httpParams.put("sign", signString)
        }
        OkGo.put<String>(GlobalAPI.acceptOrder)
                .params(httpParams)
                .execute(object : StringCallback() {

                    override fun onStart(request: Request<String, out Request<*, *>>?) {
                        super.onStart(request)
                        loadingDialog.show(mFragmentManager, "loadDialog")
                    }

                    override fun onFinish() {
                        super.onFinish()
                        loadingDialog.dismissAllowingStateLoss()
                    }

                    override fun onSuccess(response: Response<String>) {
                        listener?.requestSuccess(response.body())

                    }

                    override fun onError(response: Response<String>) {
                        super.onError(response)
                        Toast.makeText(mContext, "服务器异常", Toast.LENGTH_SHORT).show()
                    }
                })

    }

    /**
     * 上传图片
     *
     * @param sendImage
     * @param files
     * @param listener
     */
    fun sendImage(sendImage: String?, files: List<File>, listener: NetWorkHelperBack) {

        OkGo.post<String>(sendImage)
                .addFileParams("images", files)
                .execute(object : ProgressDialogCallBack(mContext) {

                    override fun onSuccess(response: Response<String>) {
                        listener.requestSuccess(response.body())

                    }

                    override fun onError(response: Response<String>) {
                        super.onError(response)
                        Toast.makeText(mContext, "服务器异常", Toast.LENGTH_SHORT).show()
                    }
                })
    }


    /**
     * 对参数进行签名
     */

    private fun sign(params: HttpParams): String? {
        val stringBuilder = StringBuilder()
        val sortedDescending = params.urlParamsMap.keys.sorted()


        if (sortedDescending.size == 1) {
            if (sortedDescending[0] == "access_token") {
                return ""
            }
        }
        for (key in sortedDescending) {
            if (key != "access_token") {
                stringBuilder.append("$key=").append(params.urlParamsMap.getValue(key)).append("&")
            }

        }
        stringBuilder.append("signkey=").append(Config.SIGN)
        val toString = stringBuilder.toString()
        val replace = toString.replace("[", "").replace("]", "")
        val signString = MD5Util.md5(replace)
        return signString
    }


    /**
     * 请求回调
     */
    interface NetWorkHelperBack {
        /**
         * 网络请求成功
         *
         * @param json
         */
        fun requestSuccess(json: String)

        /**
         * 网络请求失败
         */
        fun requestFail()
    }
}
